import { all, call, put, takeLatest } from "redux-saga/effects";
import { Creators as ArticleCreators } from "redux/actions/article";
import { ArticleTypes } from "redux/constants";
import { api } from "redux/api";
import interceptResponse from "redux/api/interceptResponse";
import interceptError from "redux/api/interceptError";

function* articleList({ payload }) {
  try {
    const { page, limit } = payload;
    const response = yield call(
      api.get,
      `/article/?page=${page}&limit=${limit}`
    );
    yield interceptResponse(response);
    if (response.data?.code !== 1000) {
      throw response;
    }
    console.log("request success response11111===>", response.data);
    yield put(ArticleCreators.getListSuccess(response.data));
  } catch (err) {
    yield interceptError(ArticleCreators.getListFailure, err);
  }
}

function* articlePublish({ payload }) {
  try {
    const { token, title, content } = payload;
    yield call(api.setHeader, "Authorization", `Bearer ${token}`);
    const response = yield call(api.post, `/article/add`, {
      title: title,
      content: content,
    });
    yield interceptResponse(response);
    if (response.data?.code !== 1000) {
      throw response;
    }
    // console.log("request success response===>", response.data);
    yield put(ArticleCreators.publishSuccess(response.data));
    yield call(Router.replace, { pathname: "/" });
  } catch (err) {
    yield interceptError(ArticleCreators.publishFailure, err);
  }
}

export default function* () {
  yield all([
    takeLatest(ArticleTypes.GET_LIST_REQUEST, articleList),
    takeLatest(ArticleTypes.PUBLISH_REQUEST, articlePublish),
  ]);
}
